package com.neusoft.yiyang.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.yiyang.common.entity.customer.Customer;
import com.neusoft.yiyang.common.entity.medical.DrugDict;
import com.neusoft.yiyang.common.entity.medical.MedicalRecord;
import com.neusoft.yiyang.common.entity.medical.MedicationOrder;
import com.neusoft.yiyang.common.entity.task.CareTask;
import com.neusoft.yiyang.common.enums.OrderStatus;
import com.neusoft.yiyang.common.enums.TaskStatus;
import com.neusoft.yiyang.common.enums.TaskType;
import com.neusoft.yiyang.medical.client.CustomerClient;
import com.neusoft.yiyang.medical.client.TaskClient;
import com.neusoft.yiyang.medical.mapper.DrugDictMapper;
import com.neusoft.yiyang.medical.mapper.MedicationOrderMapper;
import com.neusoft.yiyang.medical.service.MedicationOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.*;

@Service
public class MedicationOrderServiceImpl implements MedicationOrderService {

    @Autowired
    private MedicationOrderMapper medicationOrderMapper;

    @Autowired
    private DrugDictMapper drugDictMapper;

    @Autowired
    private TaskClient taskClient;

    @Autowired
    private CustomerClient customerClient;

    @Override
    @Transactional
    public void createMedicationOrder(MedicationOrder medicationOrder) {
        medicationOrderMapper.insert(medicationOrder);
        // 2. 获取药品信息
        DrugDict drug = drugDictMapper.selectById(medicationOrder.getDrugId());

        // 3. 生成护理任务
        generateCareTasks(medicationOrder, drug);

    }
    private void generateCareTasks(MedicationOrder order, DrugDict drug) {
        Integer customerId = order.getCustomerId();
        Integer days = order.getDays();
        Integer freqPerDay = drug.getFreqPerDay();
        Date startDate = order.getOrderTime();
        Customer customer = customerClient.getCustomerById(order.getCustomerId());
        // 根据每日服用次数获取固定的服药时间点
        List<Integer> taskHours = getFixedDoseHours(freqPerDay);

        // 为每一天生成对应次数的护理任务
        for (int day = 0; day < days; day++) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            calendar.add(Calendar.DAY_OF_MONTH, day + 1);
            Date scheduledDate = calendar.getTime();

            // 为每个固定时间点生成任务
            for (int hour : taskHours) {
                CareTask careTask = new CareTask();
                careTask.setCustomerId(customerId);
                careTask.setCaretakerId(customer.getCaretakerId());
                careTask.setTaskType(TaskType.medication);
                careTask.setRefId(order.getMedicationOrderId());
                careTask.setStatus(TaskStatus.pending);
                careTask.setQuantity(1.0);

                // 设置计划执行时间（固定时间点）
                careTask.setScheduledTime(setTaskTime(scheduledDate, hour));
                System.out.println(careTask);
                // 添加护理任务
                taskClient.createTask(careTask);
            }
        }
    }
    /**
     * 根据每日服用次数获取固定的服药时间点（小时）
     */
    private List<Integer> getFixedDoseHours(Integer freqPerDay) {
        switch (freqPerDay) {
            case 1:
                return Collections.singletonList(14); // 一天一次：14:00
            case 2:
                return Arrays.asList(8, 20); // 一天两次：8:00和20:00
            case 3:
                return Arrays.asList(8, 14, 20); // 一天三次：8:00, 14:00, 20:00
            case 4:
                return Arrays.asList(7, 11, 15, 19); // 一天四次：7:00, 11:00, 15:00, 19:00
            default:
                // 默认均分（可根据需求调整）
                List<Integer> hours = new ArrayList<>();
                for (int i = 0; i < freqPerDay; i++) {
                    hours.add(8 + (i * 24 / freqPerDay)); // 从8点开始均分
                }
                return hours;
        }
    }

    /**
     * 设置任务时间（固定小时，分钟和秒为0）
     */
    private Date setTaskTime(Date scheduledDate, int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(scheduledDate);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }



    @Override
    public List<MedicationOrder> getAllMedicationOrders() {
        return medicationOrderMapper.selectList(null);
    }

    @Override
    public List<MedicationOrder> getMedicationOrdersByCustomerId(Integer customerId) {
        return medicationOrderMapper.selectByCustomerId(customerId);
    }

    @Override
    public void updateMedicationOrder(MedicationOrder medicationOrder) {
        medicationOrderMapper.updateById(medicationOrder);
    }

    @Override
    public void deleteMedicationOrder(Integer medicationOrderId) {
        MedicationOrder medicationOrder = medicationOrderMapper.selectById(medicationOrderId);
        medicationOrder.setStatus(OrderStatus.archived);
        medicationOrderMapper.updateById(medicationOrder);
        taskClient.deleteMedicationTask(medicationOrder.getCustomerId(), medicationOrder.getMedicationOrderId());
    }

    //careTask中的refId查询对应的药物
    @Override
    public MedicationOrder getByMedicalRecordId(Integer medicationOrderId) {
        return medicationOrderMapper.selectById(medicationOrderId);
    }

    //根据CustomerId获取药物医嘱和药物信息
    @Override
    public List<Map<String, Object>> getMedicationByCustomerId (Integer customerId) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<MedicationOrder>  medicationOrderList = medicationOrderMapper.selectByCustomerId(customerId);
        for (MedicationOrder medicationOrder : medicationOrderList) {
            DrugDict drugDict = drugDictMapper.selectById(medicationOrder.getDrugId());
            Map<String, Object> map = new HashMap<>();
            map.put("medicationOrder", medicationOrder);
            map.put("drugDict", drugDict);
            result.add(map);
        }
        return result;
    }
}
